//
//  XLVideoViewController.m
//  XLPersonCenter
//
//  Created by 宋振 on 2018/7/23.
//  Copyright © 2018年 夜幕繁华. All rights reserved.
//

#import "XLVideoViewController.h"

#import "XLHTTPSessionManager+Camgirl.h"
#import <AFHTTPSessionManager.h>

#import "XLUserDataCell.h"

#import "XLPPCollectionViewCell.h"
#import "XLPPHeaderView.h"
#import "XLPPFooterView.h"

#import "XLPPCamgirlVideoModel.h"

#import "CustomerAVPlayerView.h"
#import <MJRefresh.h>

@interface XLVideoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CustomerDelegate>

@property (nonatomic, strong) CustomerAVPlayerView *  customerView;

@property (nonatomic, strong) UICollectionView             *collectionView;

//数据
@property (nonatomic, strong) NSMutableArray *  dataArray;

@property (nonatomic, assign) BOOL                          userInfoIsLoading;
@property (nonatomic, assign) BOOL                          guardianIsLoading;
@property (nonatomic, assign) BOOL                          videoListIsLoading;
@property (nonatomic, assign) BOOL                          guardianIsEmpty;
@property (nonatomic, assign) BOOL                          videoListIsEmpty;

@end

@implementation XLVideoViewController
{
    NSInteger page;
}

static NSString *const identifier = @"tempCell";

#define kMaxWidth   self.view.bounds.size.width

#define kMaxHeight  self.view.bounds.size.height

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    page = 1;
    
    //请求数据
    [self requestSource];
    
    //设置界面显示
    [self setCustomeView];
    
    
}

#pragma mark    -   -   -请求数据-  -   -
- (void)requestSource
{
    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
    manager.cachePloy = XLHTTPCachePloy_Server;
    
    [[manager XLV2GET:@"/api/v2/DynamicVideo/GetAnchorDynamicVideo" parameters:@{@"userId":self.userId,@"pageSize":@"10",@"pageIndex":@(page)} resultClass:nil] subscribeNext:^(id x) {
        
        if (page == 1) {
            
            if (self.dataArray.count > 0) {
                [self.dataArray removeAllObjects];
            }
        }
        
        //是否将数据拉取完了
        if (self.dataArray.count < page*10) {
            self.collectionView.mj_footer.hidden = YES;
        }else{
            self.collectionView.mj_footer.hidden = NO;
        }
        
        [self.dataArray addObjectsFromArray:x];
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:personCenterProxyHeaderRefresh object:nil];
        
        //是否请求到数据
        if (self.dataArray.count > 0) {
            page ++;
            [self.collectionView.mj_footer endRefreshing];
        }else{
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        
        self.videoListIsLoading = NO;
        self.videoListIsEmpty = self.dataArray.count == 0;
        
        [self.collectionView reloadData];
        
    } error:^(NSError *error) {
        
        [self.collectionView.mj_footer endRefreshing];
        
        self.videoListIsLoading = NO;
        self.videoListIsEmpty = YES;
    }];
    
}

#pragma mark    -   -   -设置界面显示-    -   -

- (void)setCustomeView
{
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//        layout.itemSize = CGSizeMake((ScreenWidth - 2) / 3.0, (ScreenWidth - 2) / 3.0 / 5.0 * 7);
    layout.itemSize = CGSizeMake((ScreenWidth-5)/2, 220);
    layout.minimumLineSpacing = 1;
    layout.minimumInteritemSpacing = 5;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    if (@available(iOS 11.0, *)) {
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [_collectionView registerClass:[XLPPCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([XLPPCollectionViewCell class])];
    [_collectionView registerClass:[XLPPHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([XLPPHeaderView class])];
    [_collectionView registerClass:[XLPPFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([XLPPFooterView class])];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"HeaderHost"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self requestSource];
        
    }];
    
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            //self.isSelf
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
                make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
            } else {
                make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
                
            }
        }];
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XLPPCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XLPPCollectionViewCell class]) forIndexPath:indexPath];
    cell.backgroundColor = [UIColor lightGrayColor];
    XLPPCamgirlVideoModel *model = [self.dataArray objectAtIndex:indexPath.row];
    
    NSDictionary *dic = self.dataArray[indexPath.row];
    
    [cell.coverImageView setImageWithURL:[NSURL URLWithString:K_DEFULT(dic[@"PicUrl"])] placeholder:[UIImage imageNamed:@""]];
    
    //播放
    NSString *viewNum = [NSString stringWithFormat:@"%@",dic[@"ViewNum"]];
    
    //喜欢
    NSString * likeNum = [NSString stringWithFormat:@"%@",dic[@"LikeNum"]];
    
    NSString *play = [NSString stringWithFormat:@"%@播放 %@喜欢",viewNum,likeNum];
    
    //名称
    NSString *titleName = K_DEFULT(dic[@"Title"]);
    
    cell.playCollect.text = play;
    cell.videoName.text = titleName;

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    
    if(self.videoListIsEmpty)
    {
        XLPPFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([XLPPFooterView class]) forIndexPath:indexPath];
        
        self.videoListIsEmpty ? [footerView showEmptyView] : [footerView hideEmptyView];
        
        return footerView;
    }else
    {
        UICollectionReusableView *reusableview = nil;
        if (kind == UICollectionElementKindSectionFooter) {
            if (reusableview == nil) {
                reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"HeaderHost" forIndexPath:indexPath];
            }
        }
        UIView * footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 103)];
        footerView.backgroundColor = KWhiteColor;
        [reusableview addSubview:footerView];
        return reusableview;
    }
    
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (self.dataArray.count <= 0) {
        return CGSizeMake(ScreenWidth, 220);
    }else{
        return CGSizeMake(ScreenWidth, 103);
    }
}

#pragma mark - UICollectionViewDelegate
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    if (scrollView.contentOffset.y < 0) {
//        [self.headerView.userInfoView.coverImageView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.view.mas_top);
//        }];
//    } else {
//        [self.headerView.userInfoView.coverImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo(self.headerView.userInfoView);
//        }];
//        CGFloat alpha1 = scrollView.contentOffset.y / 100 > 1 ? 1 : scrollView.contentOffset.y / 100;
//        self.navBarView.backgroundColor = RGBA(26, 25, 38, alpha1);
//        self.navBarView.backButton1.alpha = 1 - alpha1;
//        self.navBarView.moreButton1.alpha = 1;
//        self.navBarView.moreButton2.alpha = 1;
//
//        self.navBarView.backButton2.alpha = alpha1;
//        self.navBarView.titleLabel.alpha = alpha1;
//        //        self.statusBarIsDefault = alpha1 == 1;
//    }
//}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    XLPPCamgirlVideoModel *model = self.dataArray[indexPath.item];
    
    NSDictionary *dic = self.dataArray[indexPath.item];
    
    _customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:dic[@"PlayUrl"] isFileUrl:NO];
    _customerView.Delegate = self;

    [_customerView.player play];
    [_customerView.controlView setPlayButtonSelected:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:_customerView];
    
    if (self.videoDelegate && [self.videoDelegate respondsToSelector:@selector(videoDidSelectActionWithIndexPath:)]) {
        [self.videoDelegate videoDidSelectActionWithIndexPath:indexPath];
    }

//    [self analyticsEvent2];
}


#pragma mark - CustomerDelegate
- (void)clickBackBtnVideoPlay {
    [_customerView.player pause];
    [_customerView removeFromSuperview];
    _customerView = nil;
}

- (void)videoIsStartToPlay {
    
}

#pragma mark    -   -   -父类方法-  -   -
-(void)scrollViewToTop
{
    [self.collectionView setContentOffset:CGPointZero animated:NO];
}

- (void)beginHeaderRefresh
{
    page = 1;
    
    [self requestSource];
    
}

#pragma mark    -   -   -懒加载-   -   -

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        self.dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    
    return _dataArray;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
